<template>
  <div class="page-login">
    <van-nav-bar left-arrow @click-left="$router.back()" title="登 录"></van-nav-bar>
    <van-cell-group>
      <van-field
        v-model.trim="loginForm.mobile"
        label="手机号"
        placeholder="请输入手机号"

        @blur="checkMobile"
        :error-message="msg.mobile"
      />
      <van-field v-model="loginForm.code" label="验证码" placeholder="请输入验证码"  @blur="checkCode"
      :error-message="msg.code">
        <van-button class="p5" slot="button" size="mini" type="primary">发送验证码</van-button>
      </van-field>
    </van-cell-group>
    <div class="btn_box">
      <van-button type="info" @click="login" block round>登 录</van-button>
    </div>
  </div>
</template>
<script>
import { login } from '@/api/user.js'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      loginForm: {
        mobile: '13911111111',
        code: '246810'
      },
      msg: {
        mobile: '',
        code: ''
      }
    }
  },
  methods: {
    ...mapMutations(['changeUser']),
    checkMobile () {
      if (!this.loginForm.mobile) {
        this.msg.mobile = '手机号不能为空'
        return false
      }
      if (!(/^1[3-9]\d{9}$/).test(this.loginForm.mobile)) {
        this.msg.mobile = '手机号格式错误'
        return false
      }
      this.msg.mobile = ''
    },
    checkCode () {
      if (!this.loginForm.code) {
        this.msg.code = '验证码不能为空'
      }
      if (!(/^\d{6}$/).test(this.loginForm.code)) {
        this.msg.code = '验证码需要6位'
        return false
      }
      this.msg.code = ''
    },
    async login () {
      this.checkMobile()
      this.checkCode()
      if (this.msg.mobile || this.msg.code) return false
      console.log('ok')
      try {
        const data = await login(this.loginForm)
        console.log(data)
        this.changeUser(data)
        this.$toast.success('成功登录')
        this.$router.push(this.$route.query.redirect || '/user')
      } catch (e) {
        this.$toast.fail('登录失败')
        console.log(e)
      }
    }
  }
}
</script>

<style  scoped lang="less">
.p5 {
  padding: 0 5px;
}
.btn_box {
  padding: 10px;
  .van-button {
    height: 32px;
    line-height: 30px;
  }
}
</style>
